<script>
export default {
  name: 'DMenu',
  props: {
    mode: {
      type: String,
      default: 'vertical'
    },
    selectedKeys: {
      type: Array
    },
    value: {
      type: Array
    },
    itemClassName: {
      type: String,
      default: 'menu-item-container'
    },
    items: {
      type: [Array, Object],
      default: () => []
    },
    itemKey: {
      type: String
    }
  },
  methods: {
    handleClick(e) {
      this.$emit('click', e);
    },
    renderMenu(items) {
      const { itemClassName, itemKey } = this;
      return Object.entries(items).map(([index, item]) => {
        const { itemDisabled, children } = item;
        const key = itemKey ? item[itemKey] : index;
        if (children) {
          return (
            <a-sub-menu
              key={key}
              popupClassName="tw-menu-submenu-height"
              scopedSlots={{
                title: () => this.$scopedSlots.item(item)
              }}
            >
              {this.renderMenu(children)}
            </a-sub-menu>
          );
        }
        return (
          <a-menu-item
            key={key}
            class={itemClassName}
            disabled={itemDisabled}
            {...item}
          >
            {this.$scopedSlots.item(item)}
          </a-menu-item>
        );
      });
    }
  },
  render() {
    const props = {};
    if (this.mode) {
      props.mode = this.mode;
    }
    if (this.selectedKeys) {
      props.selectedKeys = this.selectedKeys;
    }
    if (this.value) {
      props.selectedKeys = this.value;
    }
    const on = {
      click: this.handleClick
    };

    return (
      <a-menu props={props} on={on}>
        {Object.entries(this.items).length === 0 && this.$slots.default}
        {Object.entries(this.items).length > 0 && this.renderMenu(this.items)}
      </a-menu>
    );
  }
};
</script>

<style lang="scss">
.tw-menu-submenu-height {
  .tw-menu {
    max-height: 450px !important;
    overflow-y: auto;
  }
}
</style>

<style lang="scss" scoped>
.menu-item-container {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.menu-item-container:hover {
  background-color: #edf2f8;
  color: #666666;
}
.tw-menu-item-selected {
  font-weight: 500;
}
.menu-item-icon {
  height: 28px;
  display: flex;
  align-items: center;
}
.menu-item-icon:hover {
  background-color: #edf2f8;
  color: #666666;
}
::v-deep .tw-menu-submenu-title {
  padding-right: 32px;
}
</style>
